Answer:

Name: Amy; Number: 123-4567

The toString() method is automatically called to get the String that println() requires.

Testing for Equality

Examine the equals() method:

class Entry
{
  private String name;
  private String number;

  . . . . .

  // methods

  public boolean equals( Object other )
  {
    return getName().equals( ((Entry)other).getName() );
  }

  . . . . . 
}

All classes have an equals( Object ) method because the Object class defines it and all classes descend from it. (You may wish to look at the Java documentation for Object.) Most classes override the method with a more appropriate method.

The parameter list is (Object other). This says that equals() will be used with a reference to any other object. However, in our particular application we want to compare two Entry objects with each other. (One entry will contain the name we are searching for; the other will be an entry in an ArrayList.)

We know what the parameter will be (since we are writing the code), but the compiler does not. Without more specific information, the compiler will assume only the methods and members of Object. To tell the compiler what to expect, a type cast must be used:

    return name.equals( ((Entry)other).getName() );

This tells the compiler that other is a reference to an Entry. This must be done to access the getName() method of the Entry object.

You might wonder why the method is not written this way:

  public boolean equals( Entry other )
  {
    return name.equals( other.name );
  }

This is a correct method, but it does not override the equals(Object) method that all objects have. That is the method that is used with the indexOf() method. We must override it to use the indexOf(Object) method of ArrayList:

int indexOf(Object element)    //  Search for the first occurrence of 
                               //  element, testing for equality 
                               //  using the equals(Object) method of element. 

QUESTION 22:

What will the compiler do with the following method:

class Entry
{
  . . . . .

  // methods
  public boolean equals( Object other )
  {
    return getName().equals( other.getName() );
  }

  . . . . . 
}